package com.n5x.controller.front.shopping;

import com.n5x.common.base.JsonModel;
import com.n5x.common.base.ResponseCode;
import com.n5x.common.base.TokenModel;
import com.n5x.controller.BaseController;
import com.n5x.model.shopping.ShoppingCart;
import com.n5x.model.user.UserInfo;
import com.n5x.service.IShoppingService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 前台购物车接口
 * 需要用户token
 */
@Controller
@RequestMapping("/front/shopping/cart")
public class CartController extends BaseController {


    @InitBinder("userInfo")
    public void initBinderUserInfo(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("userInfo.");
    }

    @Autowired
    private IShoppingService iShoppingService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonModel addShoppingCart(String token, @ModelAttribute UserInfo userInfo) {
        try {
            List<ShoppingCart> shoppingCartList = userInfo == null ? null : userInfo.getShoppingCarts();
            if (CollectionUtils.isEmpty(shoppingCartList)) {
                return getResult(ResponseCode.Common_ParamError, "商品不能为空");
            }
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            logger.info("[添加购物车]shoppingCarts:{},userId:{}", new Object[]{ArrayUtils.toArray(shoppingCartList)}, userId);
            iShoppingService.saveShoppingCart(userId, shoppingCartList);
            return getResult(ResponseCode.Common_Success, "填加购物车成功");
        } catch (Exception e) {
            logger.error("[添加购物车失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public JsonModel updateShoppingCartQty(String token, @RequestParam(value = "shoppingCartId", required = false) String shoppingCartId, @RequestParam(value = "qty", required = false) Integer qty) {
        try {
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            logger.info("[更新购物车数量]shoppingCartId:{},qty:{},userId:{}", new Object[]{shoppingCartId, qty, userId});
            if (StringUtils.isBlank(shoppingCartId)) {
                return getResult(ResponseCode.Common_ParamError, "购物车ID不能为空");
            }
            if (qty == null) {
                return getResult(ResponseCode.Common_ParamError, "商品数量不能为空");
            }
            ShoppingCart shoppingCart = iShoppingService.findShoppingCart(shoppingCartId);
            if (shoppingCart != null && shoppingCart.getFkUser().equals(userId)) {
                shoppingCart.setQty(qty);
                iShoppingService.saveShoppingCart(shoppingCart);
                return getResult(ResponseCode.Common_Success, "修改购物车成功");
            }
            return getResult(ResponseCode.Common_DataNotFound, "修改购物车失败，购物车数据不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/del")
    @ResponseBody
    public JsonModel delShoppingCart(String token, String shoppingCartId) {
        try {
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            logger.info("[删除购物车]shoppingCartId:{},userId:{}", new Object[]{shoppingCartId, userId});
            if (StringUtils.isBlank(shoppingCartId)) {
                return getResult(ResponseCode.Common_ParamError, "购物车ID不能为空");
            }
            ShoppingCart shoppingCart = iShoppingService.findShoppingCart(shoppingCartId);
            if (shoppingCart != null && shoppingCart.getFkUser().equals(userId)) {
                iShoppingService.deleteShoppingCart(shoppingCartId);
                return getResult(ResponseCode.Common_Success, "删除购物车成功");
            } else {
                return getResult(ResponseCode.Common_DataNotFound, "不能删除其它用户购物车");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public JsonModel findShoppingCart(String token) {
        try {
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            logger.info("[按用户查询购物车]USER_ID:{}", userId);
            List<ShoppingCart> shoppingCartList = iShoppingService.findShoppingCartByUser(userId);
            return getResult(shoppingCartList);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }
}